package worker

import (
	"cron-go/internal/pkg/crontab/dao"
	"cron-go/internal/pkg/crontab/enum"
	"cron-go/internal/pkg/crontab/models"
	"cron-go/internal/pkg/utils/httpclient"
	"fmt"

	"github.com/go-liam/util/conv"
)

const HttpTimeOut = 5

type HttpConfig struct {
	Type   string            `json:"type" `
	Url    string            `json:"url" `
	Method string            `json:"method" `
	Header map[string]string `json:"header" `
}

//http 工作者:
func HttpWork(t *models.TaskMysqlModel) bool {
	if t.Config == "" {
		return false
	}
	d := new(HttpConfig)
	conv.JsonStringToStruct(t.Config, d)
	v := httpclient.RequestData(d.Method, d.Url, t.Command, d.Header, HttpTimeOut)

	status := enum.DoStatusFail
	if v.StatusCode == 200 {
		status = enum.DoStatusSuccess
	}
	//add log
	ml := new(models.TaskLogMysqlModel)
	ml.TaskID = t.ID
	ml.DoStatus = status
	result := conv.StringLeft(v.Body, 200)
	ml.Info = fmt.Sprintf(`{"type":"http","code":%v,"result":"%v"}`, v.StatusCode, result)
	new(dao.LogDao).Create(ml)
	//finish
	FinishWorker(t, status)
	return (status == enum.DoStatusSuccess)
}
